/*
 * Copyright (c) 2017. Visionet and/or its affiliates. All right reserved.
 * VISIONET PROPRIETARY/CONFIDENTIAL.
 */
package com.visionet.jumper.core.support.spring;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

/**
 * @author TC.Ubuntu
 * @since 2017/7/3.
 */
@Service
@Lazy(false)
public final class SpringLocator implements ApplicationContextAware {

	private static ApplicationContext applicationContext;

	@Override
	public void setApplicationContext(ApplicationContext applicationContext)
			throws BeansException {
		SpringLocator.applicationContext = applicationContext;
	}

	public static ApplicationContext getApplicationContext() {
		return SpringLocator.applicationContext;
	}

	/**
	 * 获取bean实例
	 * @param name bean注册的id
	 * @return Object bean实例
	 * @throws org.springframework.beans.BeansException
	 *
	 */
	@SuppressWarnings("unchecked")
	public static <T> T getBean(String name) throws BeansException {
		return (T) applicationContext.getBean(name);
	}

	public static <T> T getBean(String name, Class<T> type) {
		Assert.hasText(name);
		Assert.notNull(type);
		return applicationContext.getBean(name, type);
	}

	public static <T> T getBean(Class<T> clazz){
		Assert.notNull(clazz);
		return applicationContext.getBean(clazz);
	}
}
